package engine.display
{
	import engine.data.ModelLocator;
	import engine.net.event.CustomMsgEvent;

	/**
	 *	消息 
	 * @author lw
	 * 
	 */
	public class InterceptMsgLogic
	{
		private static	 var _self	:	InterceptMsgLogic;
		
		public static function getInstance():InterceptMsgLogic
		{
			if ( _self == null )
			{
				_self = new InterceptMsgLogic();
			}
			return _self;
		}
		
		private var _model	 	: ModelLocator;
		
		private var _msgList	: Array = [];	
		
		public function InterceptMsgLogic()
		{
			_model = ModelLocator.getInstance();
		}
		
		public function intercept( msgID : String ):void
		{
			_model.addEventListener( msgID, onReceiveMsg, false, 1 );
			
			function onReceiveMsg( evt : CustomMsgEvent ):void
			{
				_msgList.push( [ msgID, evt.pList, onReceiveMsg ] );
				
				evt.stopImmediatePropagation();
			}
		}
		
		public function sendAll():void
		{
			for each( var msg : Array in _msgList )
			{
				_model.removeEventListener( msg[ 0 ], msg[ 2 ] );
				
				_model.dispatchEvent( new CustomMsgEvent( msg[ 0 ], msg[ 1 ] ) );
			}
			
			_msgList = [];
		}
		
		public function sendMsg( msgId : String ):void
		{
			var leng : int = _msgList.length;
			
			for( var i : int = 0; i < leng; i++ )
			{
				if( _msgList[ 0 ] == msgId )
				{
					var msg : Array = _msgList.splice( i, 1 )[ 0 ];
	
					_model.removeEventListener( msg[ 0 ], msg[ 2 ] );
					_model.dispatchEvent( new CustomMsgEvent( msg[ 0 ], msg[ 1 ] ) );
					
					break;
				}
			}
		}
	}
}